//
//  ViewController.m
//  XiTongMap
//
//  Created by lanou3g on 15/11/4.
//  Copyright © 2015年 lanou3g. All rights reserved.
//


#import "MapViewController.h"
#import <Foundation/Foundation.h>
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>

#define kScreenWidth [UIScreen mainScreen].bounds.size.width
#define kScreenHeight [UIScreen mainScreen].bounds.size.height

@interface MapViewController ()<CLLocationManagerDelegate, MKMapViewDelegate, UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate>

@property (nonatomic, strong)CLLocationManager *locationManager;
@property (nonatomic, strong)MKMapView *mapView;
@property (nonatomic, strong)CLGeocoder *geocoder;
@property (nonatomic, strong)MKLocalSearch *search;
@property (nonatomic, assign)MKCoordinateRegion region;
@property (nonatomic, strong)MKLocalSearchRequest *request;

@property (nonatomic, strong)CLLocation *localLocation;

@property (nonatomic, strong)UITextField *searchTextField;
@property (nonatomic, strong)UIButton *searchButton;
@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong)UILabel *lineLabel;
@property (nonatomic, strong)NSMutableArray *dataArray;

@property (nonatomic, strong)MKPointAnnotation *pointAnnotation;

@property (nonatomic, assign)BOOL isSucceed;

@end

@implementation MapViewController


- (void)viewWillDisappear:(BOOL)animated{

    [self.locationManager stopUpdatingLocation];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.view.backgroundColor = [UIColor whiteColor];
    
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 7.0) {
        self.edgesForExtendedLayout = UIRectEdgeNone; // 设置边距
    }
    
    
    [self addMapViews];
    [self addSubViews];
    [self setNavbar];

}
#pragma mark -- 设置Navbar
- (void)setNavbar{
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithTitle:@"定位" style:UIBarButtonItemStylePlain target:self action:@selector(actionRightItem:)];
    self.navigationItem.rightBarButtonItem = rightItem;
    rightItem.tintColor = [UIColor whiteColor];
    
    UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"Returns"] style:UIBarButtonItemStylePlain target:self action:@selector(actionBackButton:)];
    backButton.tintColor = [UIColor whiteColor];
    self.navigationItem.leftBarButtonItem = backButton;
    
    
}
#pragma mark -- 点击方法
- (void)actionBackButton:(UIBarButtonItem *)sender{
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)actionRightItem:(UIBarButtonItem *)sender{
    [self pop];
}

#pragma mark === 布局地图
- (void)addMapViews{
    self.locationManager  = [[CLLocationManager alloc] init];
    self.locationManager.delegate = self;
    // 定位精度
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    // 设置多少米更新一次
    self.locationManager.distanceFilter = 100;
    // 什么时候开始请求信息
    [self.locationManager requestAlwaysAuthorization];
    // 开始请求
    [self.locationManager startUpdatingLocation];


    self.searchTextField = [[UITextField alloc] initWithFrame:CGRectMake(kScreenWidth*0.05, (kScreenHeight-64)*0.01, kScreenWidth*0.7, (kScreenHeight-64)*0.06)];
    self.searchTextField.delegate = self;
    self.searchTextField.returnKeyType = UIReturnKeyDone;
    self.searchTextField.borderStyle = UITextBorderStyleRoundedRect;
    [self.view addSubview:self.searchTextField];
    
    
    self.searchButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.searchButton.frame = CGRectMake(CGRectGetMaxX(self.searchTextField.frame), CGRectGetMinY(self.searchTextField.frame), kScreenWidth*0.2, CGRectGetHeight(self.searchTextField.frame));
    [self.searchButton setTitle:@"搜索" forState:UIControlStateNormal];
    [self.searchButton setTitleColor:kFindListCellLabelTextColor forState:UIControlStateNormal];
    [self.searchButton addTarget:self action:@selector(actionSearch:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.searchButton];
    
    
    // 地图初始化
    self.mapView = [[MKMapView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.searchTextField.frame)+(kScreenHeight-64)*0.01, kScreenWidth, (kScreenHeight-64)*0.52)];
    self.mapView.delegate = self;
    // 设置地图跟随位置移动
//    self.mapView.userTrackingMode = MKUserTrackingModeFollow;
    // 设置地图样式
    self.mapView.mapType = MKMapTypeStandard;
    // 地图上是否显示用户位置
//    self.mapView.showsUserLocation = YES;
    // 比例尺
    [self.mapView setZoomEnabled:YES];
    self.mapView.showsScale = YES;
    
    
    [self.view addSubview:self.mapView];
    
    self.geocoder = [[CLGeocoder alloc] init];
}
#pragma --- 布局视图
- (void)addSubViews{
    
    UIButton *button1 = [UIButton buttonWithType:UIButtonTypeCustom];
    button1.frame = CGRectMake(0, CGRectGetMaxY(self.mapView.frame), kScreenWidth/3, (kScreenHeight-64)*0.07);
    button1.tag = 101;
    [button1 setTitle:@"商场" forState:UIControlStateNormal];
    [button1 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [button1 addTarget:self action:@selector(actionButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button1];
 
    UIButton *button2 = [UIButton buttonWithType:UIButtonTypeCustom];
    button2.frame = CGRectMake(CGRectGetMaxX(button1.frame), CGRectGetMinY(button1.frame), CGRectGetWidth(button1.frame), CGRectGetHeight(button1.frame));
    [button2 setTitle:@"写字楼" forState:UIControlStateNormal];
    [button2 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    button2.tag = 102;
    [button2 addTarget:self action:@selector(actionButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button2];
    
    UIButton *button3 = [UIButton buttonWithType:UIButtonTypeCustom];
    button3.frame = CGRectMake(CGRectGetMaxX(button2.frame), CGRectGetMinY(button2.frame), CGRectGetWidth(button2.frame), CGRectGetHeight(button2.frame));
    [button3 setTitle:@"小区" forState:UIControlStateNormal];
    [button3 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    button3.tag = 103;
    [button3 addTarget:self action:@selector(actionButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button3];
    
    self.lineLabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMinX(button1.frame), CGRectGetMaxY(button1.frame)-3, CGRectGetWidth(button1.frame), 3)];
    self.lineLabel.backgroundColor = [UIColor colorWithRed:0.341 green:0.749 blue:1.000 alpha:1.000];
    [self.view addSubview:self.lineLabel];
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(button1.frame), kScreenWidth, (kScreenHeight-64)*0.4-CGRectGetHeight(button1.frame)) style:UITableViewStylePlain];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self.view addSubview:self.tableView];
}

- (void)actionButton:(UIButton *)sender{
    
    [UIView animateWithDuration:0.3 animations:^{
        self.lineLabel.frame = CGRectMake(CGRectGetMinX(sender.frame), CGRectGetMaxY(sender.frame)-3, CGRectGetWidth(sender.frame), 3);
    }];
    if (sender.tag == 101) {
        [self search:self.latitude longitude:self.longitude naturalLanguageQuery:@"商场"];
    } else if (sender.tag == 102) {
        [self search:self.latitude longitude:self.longitude naturalLanguageQuery:@"写字楼"];
    } else {
        [self search:self.latitude longitude:self.longitude naturalLanguageQuery:@"小区"];
    }
}


#pragma mark ==== location代理方法
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
    
    self.isSucceed = YES;
    
    self.localLocation = [locations firstObject];
    [self.geocoder reverseGeocodeLocation:self.localLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        CLPlacemark *placemark = [placemarks firstObject];
        NSDictionary *dic = placemark.addressDictionary;
        NSString *name = placemark.name; // 详细地址(中國香港特別行政區中西區金融街8號)
        NSString *country = placemark.country; // 国家(中國)
        NSString *locality = placemark.locality; // 地址 (香港特別行政區)
        CLLocation *location11 = placemark.location; // 坐标
        NSString *ocea = placemark.ocean;
        NSString *inaf = placemark.inlandWater;
        self.address = placemark.name;
        self.latitude = self.localLocation.coordinate.latitude;
        self.longitude = self.localLocation.coordinate.longitude;
        [self positionPointAnnotation:placemark.name];
        CLLocationCoordinate2D location = [placemark.location coordinate];
        // 放大地图到设备所在位置, 并设置显示区域的大小 单位是米
        MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(location, 5000, 5000);
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.mapView setRegion:region animated:YES];
        });
    }];

    [self search:self.localLocation.coordinate.latitude longitude:self.localLocation.coordinate.longitude naturalLanguageQuery:@"商场"];
}

#pragma mark -- 检索周边
- (void)search:(CGFloat)latitude longitude:(CGFloat)longitude naturalLanguageQuery:(NSString *)naturalLanguageQuery{
    [self.dataArray removeAllObjects]; // 清空数组里面的数据
    // 检索参数 检索的地区的经纬度和检索的范围
    self.region = MKCoordinateRegionMakeWithDistance(CLLocationCoordinate2DMake(latitude, longitude), 500, 500);
    self.request = [[MKLocalSearchRequest alloc] init];
    // 设置检索参数
    self.request.region = self.region;
    // 设置要搜索的关键字 (例如: hotel)
    self.request.naturalLanguageQuery = naturalLanguageQuery;
    // 初始化检索
    self.search = [[MKLocalSearch alloc] initWithRequest:self.request];
    [self.search startWithCompletionHandler:^(MKLocalSearchResponse * _Nullable response, NSError * _Nullable error) {
        NSArray *mapItems = response.mapItems;
        for (MKMapItem *mapItem in mapItems) {
            [self.dataArray addObject:mapItem];
        }
        [self.tableView reloadData];
    }];
}
#pragma mark == 插大头针
- (void)positionPointAnnotation:(NSString *)name{
    [self.mapView removeAnnotation:self.pointAnnotation];
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder geocodeAddressString:name completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        CLPlacemark *placemark = [placemarks firstObject];
        
        self.address = name;
        self.latitude = placemark.location.coordinate.latitude;
        self.longitude = placemark.location.coordinate.longitude;
        
        self.pointAnnotation = [[MKPointAnnotation alloc] init];
        self.pointAnnotation.coordinate = placemark.location.coordinate;
        [self.mapView addAnnotation:self.pointAnnotation];
    }];
}


- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    if (self.isSucceed == NO) {
        if ([error code] == kCLErrorDenied) {
            [self alertControllerMessage:@"访问被拒绝"];
        } else {
            [self alertControllerMessage:@"无法获取位置信息"];
        }

    }
}

- (void)alertControllerMessage:(NSString *)message{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    [self presentViewController:alert animated:YES completion:nil];
    [self performSelector:@selector(actionAlertDismiss:) withObject:alert afterDelay:1];
}

- (void)actionAlertDismiss:(UIAlertController *)sender{
    [sender dismissViewControllerAnimated:YES completion:nil];
}


#pragma mark -- 搜索
- (void)actionSearch:(UIButton *)sender{
    if ([self.searchTextField.text isEqualToString:@""]) {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"请输入地点" preferredStyle:UIAlertControllerStyleAlert];
        [self presentViewController:alertController animated:YES completion:nil];
        [self performSelector:@selector(actionAlertDismiss:) withObject:alertController afterDelay:1];
    } else {
        [self.searchTextField resignFirstResponder];
        CLGeocoder *geocoder = [[CLGeocoder alloc] init];
        [geocoder geocodeAddressString:self.searchTextField.text completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
            CLPlacemark *placemark = [placemarks firstObject];
            self.address = placemark.name;
            self.latitude = placemark.location.coordinate.latitude;
            self.longitude = placemark.location.coordinate.longitude;
            [self search:self.latitude longitude:self.longitude naturalLanguageQuery:@"商场"];
            [self positionPointAnnotation:placemark.name];
            CLLocationCoordinate2D location = [placemark.location coordinate];
            // 放大地图到设备所在位置, 并设置显示区域的大小 单位是米
            MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(location, 5000, 5000);
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.mapView setRegion:region animated:YES];
            });
        }];
    }

}

#pragma mark -- 键盘搜索
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}


#pragma mark === tableView代理方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identifier = @"MapCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];
    }
    MKMapItem *mapItem = self.dataArray[indexPath.row];
    cell.textLabel.text = mapItem.name;
    cell.detailTextLabel.text = [NSString stringWithFormat:@"%@%@%@", mapItem.placemark.addressDictionary[@"State"], mapItem.placemark.addressDictionary[@"SubLocality"], mapItem.placemark.addressDictionary[@"Street"]];
       return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    MKMapItem *mapItem = self.dataArray[indexPath.row];
    [self positionPointAnnotation:mapItem.name];
    [self pop];
}

- (void)pop{
    [_mapDelegate transAddress:self.address latitude:self.latitude longitude:self.longitude];
    [self.navigationController popViewControllerAnimated:YES];
}

- (NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
